<template>
    <ContentWrap>
        <el-table :data="memberData">
            <el-table-column label="教师总数" align="center" prop="memberCount"/>
            <el-table-column label="专业数量" align="center" prop="majorCount"/>
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button
                        link
                        type="primary"
                        @click="openDeatilForm()"
                    >
                        查看
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </ContentWrap>

    <el-dialog title="专业分布" v-model="dialogZYFBVisible" width="420px" draggable destroy-on-close>
        <el-table :data="ZYFBData">
            <el-table-column label="专业" align="center" prop="majorName"/>
            <el-table-column label="专业人数" align="center" prop="memberCount"/>
        </el-table>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="closeZYFB">确 定</el-button>
            </span>
        </template>
    </el-dialog>

    <ContentWrap>
        <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px"
                 label-width="70px" @submit.native.prevent>
            <el-form-item label="归属学校" prop="schoolId" v-if="tenantId == 1">
                <el-select v-model="queryParams.schoolId" placeholder="请选择" class="!w-240px" filterable default-first-option clearable>
                    <el-option v-for="item in schools" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="教师工号" prop="code">
                <el-input v-model="queryParams.code" class="!w-240px" clearable
                          placeholder="请输入教师工号" @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="教师名称" prop="name">
                <el-input v-model="queryParams.name" class="!w-240px" clearable placeholder="请输入名称"
                          @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="queryParams.mobile" class="!w-240px" clearable placeholder="请输入手机号"
                          @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="专业" prop="majorId">
                <el-select v-model="queryParams.majorId" placeholder="请选择专业" clearable>
                    <el-option v-for="item in majors" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="预约状态" prop="canSub">
                <el-select v-model="queryParams.canSub" placeholder="请选择预约状态" clearable>
                    <el-option v-for="item in canSubs" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="定位权限" prop="canLocation">
              <el-select v-model="queryParams.canLocation" placeholder="请选择定位状态" clearable>
                <el-option v-for="item in canLocations" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item>
                <el-button @click="handleQuery">
                    <Icon class="mr-5px" icon="ep:search"/>
                    搜索
                </el-button>
                <el-button @click="resetQuery">
                    <Icon class="mr-5px" icon="ep:refresh"/>
                    重置
                </el-button>
                <el-button v-hasPermi="['yxt:member:create']" plain type="primary"
                           @click="openForm('create')">
                    <Icon class="mr-5px" icon="ep:plus"/>
                    新增
                </el-button>
                <el-button type="warning" plain @click="handleImport" v-hasPermi="['yxt:member:import']">
                    <Icon icon="ep:upload"/>
                    导入
                </el-button>
                <el-button type="success" plain @click="handleExport" :loading="exportLoading"
                           v-hasPermi="['yxt:member:export']">
                    <Icon icon="ep:download"/>
                    导出
                </el-button>
                <el-button type="primary" plain @click="router.push('teacherCourseData')" v-hasPermi="['yxt:member:course:data']">
                  <Icon icon="ep:reading"/>
                  查看教师总课程数据
                </el-button>
            </el-form-item>
        </el-form>
    </ContentWrap>


    <ContentWrap>
        <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="教师工号" prop="code" min-width="120"/>
            <el-table-column label="教师名称" prop="name" min-width="100"/>
            <el-table-column label="头像" prop="avatar" width="50">
                <template #default="scope">
                    <div style="width: 36px; height: 36px">
                        <el-image v-if="scope.row.avatar" :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]"
                                  preview-teleported hide-on-click-modal/>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="手机号" prop="mobile" min-width="120"/>
            <el-table-column label="归属学校" prop="schoolName"/>
            <el-table-column label="专业" prop="majors" min-width="200">
                <template #default="scope">
                    <el-tag v-for="tag in scope.row.majors" type="warning" :key="tag"
                            :disable-transitions="true" class="mr-5px">
                        {{ tag.name }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="类型" prop="type">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.YXT_USER_TYPE" :value="scope.row.type"/>
                </template>
            </el-table-column>
            <el-table-column label="性别" prop="sex">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.sex"/>
                </template>
            </el-table-column>
            <el-table-column label="状态" prop="status">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.YXT_ACTIVE_STATUS" :value="scope.row.status"/>
                </template>
            </el-table-column>
            <el-table-column label="预约权限" prop="canSub">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.canSub"/>
                </template>
            </el-table-column>
            <el-table-column label="定位权限 " prop="canLocation">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.canLocation"/>
              </template>
            </el-table-column>
            <el-table-column :formatter="dateFormatter" align="center" label="创建时间" prop="createTime" width="180"/>
            <el-table-column :width="150" align="center" label="操作" fixed="right">
                <template #default="scope">
                    <el-button link type="primary" @click="() => router.push('detail/'+scope.row.id)">
                        查看
                    </el-button>
                    <el-button v-hasPermi="['yxt:member:update']" link type="primary"
                               @click="openForm('update', scope.row.id)">
                        编辑
                    </el-button>
                    <el-button v-hasPermi="['yxt:member:delete']" link type="danger"
                               @click="handleDelete(scope.row.id)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo"
                    :total="total" @pagination="getList"/>
    </ContentWrap>

    <MemberForm ref="formRef" @success="getList"/>
    <MemberImportForm ref="importFormRef" @success="getList"/>
</template>

<script lang="ts" setup>
import {DICT_TYPE} from '@/utils/dict'
import {dateFormatter} from '@/utils/formatTime'
import {useMemberApi} from "@/api/yxt/member";
import MemberForm from "@/views/yxt/member/teacher/MemberForm.vue";
import {useMajorApi} from "@/api/yxt/major";
import {useConfirm, useMessage} from "@/components/Notice";
import router from "@/router";
import MemberImportForm from "@/views/yxt/member/teacher/MemberImportForm.vue";
import {useSchoolApi} from "@/api/yxt/school";
import {getTenantId} from "@/utils/auth";
import * as XLSX from 'xlsx';


defineOptions({name: 'YxtTeacherMember'})

const tenantId = getTenantId();

const majorApi = useMajorApi();
const memberApi = useMemberApi();
const schoolApi = useSchoolApi();
const {t} = useI18n() // 国际化

const dialogZYFBVisible = ref(false) //专业分布
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const canSubs = ref([
    {name: "可预约", id: 0},
    {name: "不可预约", id: 1}
])
const canLocations = ref([
  {name: "开启", id: 0},
  {name: "关闭", id: 1}
])
const queryParams = reactive({
    memberType: 1,
    pageNo: 1,
    pageSize: 10,
    schoolId: '',
    name: '',
    grade: undefined,
    term: undefined,
    code: '',
    mobile: '',
    canSub: undefined,
    canLocation: undefined,
    majorId: undefined,
})
const queryFormRef = ref()
const majors = ref<Array<any>>([])
const schools = ref<Array<any>>([])
const multipleSelection = ref<Array<any>>([])
const ZYFBData = ref<Array<any>>([])
const memberData = ref<Array<any>>([])  //数据汇总

const openDeatilForm = async () => {
    dialogZYFBVisible.value = true;
    ZYFBData.value = await memberApi.majorMemberCount({
        memberType: 1
    })
}

const closeZYFB = async () => {
    dialogZYFBVisible.value = false;
}

const getList = async () => {
    loading.value = true
    try {
        const data = await memberApi.getMemberPage(queryParams)
        list.value = data.list
        total.value = data.total
    } finally {
        loading.value = false
    }
}

const handleSelectionChange = (val) => {
    multipleSelection.value = val;
}
const handleQuery = () => {
    queryParams.pageNo = 1
    getList()
}

const resetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
}

const formRef = ref()
const openForm = (type: string, id?: number) => {
    formRef.value.open(type, id)
}

const handleDelete = (id: number) => {
    useConfirm(t("common.delMessage"), async () => {
        await memberApi.deleteTea(id);
        getList().finally(() => useMessage(t('common.delSuccess')));
    });
}

const importFormRef = ref()
const handleImport = () => {
    importFormRef.value.open()
}

const exportLoading = ref(false)
const handleExport = () => {
    useConfirm(t("common.exportMessage"), async () => {
        exportLoading.value = true
        try {
            if (list.value.length == 0) {
                useMessage("没有可导出数据", "warning")
                return;
            }
            const exportData = multipleSelection.value.length > 0 ? multipleSelection.value
                : await memberApi.listNoPage(queryParams);
            const formData = exportData.map(formatData)
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet(formData);
            // 将工作表添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "选中数据");
            // 生成文件
            XLSX.writeFile(wb, "老师数据.xlsx");
        } finally {
            exportLoading.value = false
        }
    });
}

const formatData = (item: any) => {
    return {
        "教师工号": item.code,
        "名称": item.name,
        // "头像": item.avatar,
        "手机号": item.mobile,
        "归属学校": item.schoolName,
        "专业": item.majors.map(major => major.name).join(","),
        "类型": item.type == 0 ? "学生" : "教师",
        "性别": item.sex == 1 ? "男" : "女",
        "状态": item.status == 1 ? "冻结" : "激活",
        "预约权限": item.canSub == 0 ? "开启" : "关闭",
        "定位权限": item.canLocation == 0 ? "开启" : "关闭",
        "创建时间": formatDateTime(item.createTime)
    }
}

//时间戳转换时间
const formatDateTime = (timestamp: any) => {
// 使用 Intl.DateTimeFormat 格式化日期时间
    const formattedDate = new Intl.DateTimeFormat('en-US', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false, // 使用 24 小时制
    }).format(new Date(timestamp));
    return formattedDate;
}

onMounted(async () => {
    await getList();
    memberData.value = await memberApi.memberData({memberType: 1})
    majors.value = await majorApi.getMajorList();
    schools.value = await schoolApi.getSimpleList();
})
</script>
